package com.cskaoyan.service.zy;

import cn.hutool.core.bean.BeanUtil;
import com.cskaoyan.bean.bo.zy.WXOrderCommentBO;
import com.cskaoyan.bean.bo.zy.WXOrderListBO;
import com.cskaoyan.bean.bo.zy.WXOrderSubmitAddress;
import com.cskaoyan.bean.bo.zy.WXOrderSubmitBO;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.common.Constant;
import com.cskaoyan.bean.marketBean.*;
import com.cskaoyan.bean.vo.zy.*;
import com.cskaoyan.mapper.marketMapper.*;
import com.cskaoyan.utils.OrderUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhangYun
 * @since 2022/12/31 11:52
 */
@Service
public class WXOrderModuleZYServiceImpl implements WXOrderModuleZYService {

    @Autowired
    private MarketOrderMapper marketOrderMapper;
    @Autowired
    private MarketCartMapper marketCartMapper;
    @Autowired
    private MarketAddressMapper marketAddressMapper;
    @Autowired
    private MarketCouponMapper marketCouponMapper;
    @Autowired
    private MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    private MarketOrderGoodsMapper marketOrderGoodsMapper;
    @Autowired
    private MarketCommentMapper marketCommentMapper;



    // TODO 分页有问题；对应状态码有问题 ,分页搞定
    // TODO 分页，我干
    @Override
    public CommonData<WXOrderListVO> orderList(WXOrderListBO parama, Integer id) {
        PageHelper.startPage(parama.getPage(), parama.getLimit());

        Integer orderStatus = getOrderStatus(parama.getShowType().intValue());
        //List<Integer> orderIds = marketOrderMapper.selectOrderIdList(orderStatus, id,parama.getPage(),parama.getLimit());
        //Integer total = marketOrderMapper.selectOrderNum(orderStatus, id);
        //Integer pages = total / parama.getLimit();

        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        if (orderStatus != null) {
            criteria.andOrderStatusEqualTo(orderStatus.shortValue());
        }
        criteria.andUserIdEqualTo(id);

        List<MarketOrder> orderList = marketOrderMapper.selectByExample(marketOrderExample);

        PageInfo pageInfo = new PageInfo<>(orderList);
        List<Integer> orderIds = new ArrayList<>();
        for (MarketOrder order : orderList) {
            orderIds.add(order.getId());
        }

        List<WXOrderListVO> orderListVO = new ArrayList<>();
        for (Integer orderId : orderIds) {
            WXOrderListVO order;
            order = marketOrderMapper.selectOrder(orderId);
            Integer orderStatusText = marketOrderMapper.selectStatus(order.getId());
            HandleOptionBean handleOptionBean = new HandleOptionBean();
            WXOrderListVO orderResult = getOrderStatusText(orderStatusText, order);
            // 团购不用写，写死
            order.setIsGroupin(false);

            orderListVO.add(orderResult);
        }
        pageInfo.setList(orderListVO);
        CommonData data = CommonData.data(pageInfo);
        /*CommonData<WXOrderListVO> data = new CommonData<>();
        data.setList(orderListVO);
        data.setPage(parama.getPage());
        data.setLimit(parama.getLimit());
        data.setTotal(total);
        data.setPages(pages);*/

        return data;
    }

    @Override
    public WXOrderSubmitVO orderSubmit(WXOrderSubmitBO param, List<Integer> cartIdList, Integer userId) {
        MarketOrder marketOrder = new MarketOrder();
        MarketOrderGoods marketOrderGoods = new MarketOrderGoods();

        // 设置用户id
        marketOrder.setUserId(userId);
        // 设置订单编号
        marketOrder.setOrderSn(OrderUtils.getOrderCode(userId));
        // 设置订单状态
        marketOrder.setOrderStatus(Constant.UNPAID_CODE.shortValue());

        /*MarketAddressExample addressExample = new MarketAddressExample();
        MarketAddressExample.Criteria criteria = addressExample.createCriteria();
        criteria.andIdEqualTo(param.getAddressId());
        criteria.andUserIdEqualTo(userId);*/
        // 获取地址信息，id唯一，所以不需要userId
        MarketAddress address = marketAddressMapper.selectByPrimaryKey(param.getAddressId());
        WXOrderSubmitAddress targetAddress = new WXOrderSubmitAddress();
        targetAddress.setMobile(address.getTel());
        targetAddress.setConsignee(address.getName());
        targetAddress.setAddress(address.getProvince() + address.getCity() + address.getCounty() + address.getAddressDetail());
        // 设置订单收货人、电话、详细地址
        BeanUtil.copyProperties(targetAddress, marketOrder);
        // 设置用户订单留言
        marketOrder.setMessage(param.getMessage());

        // 获取该购物车对应的所以商品id
        List<MarketCart> cartList = new ArrayList<>();
        for (Integer cartId : cartIdList) {
            MarketCart cart = marketCartMapper.selectByPrimaryKey(cartId);
            cartList.add(cart);
        }
        BigDecimal goodsPrice = Constant.DEFAULT_VALUE;
        for (MarketCart marketCart : cartList) {
            Short number = marketCart.getNumber();
            BigDecimal num = new BigDecimal(number);
            BigDecimal singlePrice = marketCart.getPrice().multiply(num);
            goodsPrice = goodsPrice.add(singlePrice);
        }

        // 设置商品总价格
        marketOrder.setGoodsPrice(goodsPrice);
        // 设置配送费用
        marketOrder.setFreightPrice(new BigDecimal(20));
        // 设置优惠卷价格
        MarketCouponUser marketCouponUser = marketCouponUserMapper.selectByPrimaryKey(param.getUserCouponId());
        if (marketCouponUser != null && marketCouponUser.getStatus().equals(0)) {
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(param.getCouponId());
            marketOrder.setCouponPrice(marketCoupon.getDiscount());
        }
        marketOrder.setCouponPrice(Constant.DEFAULT_VALUE);
        // 设置用户积分减免 写死
        marketOrder.setIntegralPrice(Constant.DEFAULT_VALUE);
        // 设置团购优惠价减免 写死
        marketOrder.setGrouponPrice(Constant.DEFAULT_VALUE);
        // 设置订单费用
        BigDecimal orderPrice = marketOrder.getGoodsPrice().add(marketOrder.getFreightPrice()).subtract(marketOrder.getCouponPrice());
        marketOrder.setOrderPrice(orderPrice);
        // 设置实际支付费用
        BigDecimal actualPrice = marketOrder.getOrderPrice().subtract(marketOrder.getIntegralPrice());
        marketOrder.setActualPrice(actualPrice);
        // 设置订单创建时间
        Date date = new Date();
        marketOrder.setAddTime(date);
        // 设置订单更新时间
        marketOrder.setUpdateTime(date);
        // 生成订单
        marketOrderMapper.insertSelective(marketOrder);
        // 修改该用户该优惠卷的状态为使用状态 1，表示已经使用过了
        MarketCouponUser couponUser = new MarketCouponUser();
        Short couponUserStatus = new Short((short) 1);
        couponUser.setStatus(couponUserStatus);
        couponUser.setId(param.getUserCouponId());
        marketCouponUserMapper.updateByPrimaryKeySelective(couponUser);

        // 插入order_goods表
        for (MarketCart marketCart : cartList) {
            String[] ignoreProperties = {"id", "userId", "checked", "addTime", "updateTime", "deleted"};
            BeanUtil.copyProperties(marketCart, marketOrderGoods, ignoreProperties);
            // 设置订单id，在插入的时候订单表的时候，做些配置，获得自增主键
            marketOrderGoods.setOrderId(marketOrder.getId());
            // 设置添加时间，和添加订单的时间一样
            marketOrderGoods.setAddTime(date);
            // 设置更新时间，和添加订单的时间一样
            marketOrderGoods.setUpdateTime(date);
            marketOrderGoodsMapper.insertSelective(marketOrderGoods);
        }

        WXOrderSubmitVO result = new WXOrderSubmitVO();
        result.setOrderId(marketOrder.getId());
        result.setGrouponLinkId(param.getGrouponLinkId());
      /*  List<Integer> goodsIdList = new ArrayList<>();
        for (MarketCart cart : cartList) {
            Integer goodsId = cart.getGoodsId();
            goodsIdList.add(goodsId);
        }
        for (Integer goodsId : goodsIdList) {
            MarketGoodsProductExample productExample = new MarketGoodsProductExample();
            MarketGoodsProductExample.Criteria productExampleCriteria = productExample.createCriteria();
            productExampleCriteria.andGoodsIdEqualTo(goodsId);
            List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(productExample);
        }
*/


        return result;
    }

    @Override
    public void orderPrepay(Integer orderId, Integer userId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus(Constant.PAID_CODE.shortValue());
        marketOrder.setId(orderId);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);

        // 逻辑删除cart表中的数据
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria orderGoodsExampleCriteria = marketOrderGoodsExample.createCriteria();
        orderGoodsExampleCriteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> orderGoodsList = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
        List<Integer> goodsIdList = new ArrayList<>();
        for (MarketOrderGoods orderGoods : orderGoodsList) {
            Integer goodsId = orderGoods.getGoodsId();
            goodsIdList.add(goodsId);
        }
        for (Integer goodsId : goodsIdList) {
            MarketCart marketCart = new MarketCart();
            marketCart.setDeleted(true);
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andGoodsIdEqualTo(goodsId);
            marketCartMapper.updateByExampleSelective(marketCart,marketCartExample);
        }

    }

    @Override
    public WXOrderDetailVO orderDetail(Integer orderId, Integer userId) {
        WXOrderDetailVO result = new WXOrderDetailVO();

        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
        result.setOrderGoods(marketOrderGoods);

        WXOrderDetailOrder wxOrderDetailOrder = new WXOrderDetailOrder();
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        String[] ignoreProperties = {"userId","orderStatus","integralPrice","grouponPrice","orderPrice","payId","payTime","shipSn","shipChannel","shipTime","refundAmount","refundType","refundContent","refundTime","confirmTime","comments","endTime","updateTime","deleted"};
        BeanUtil.copyProperties(marketOrder,wxOrderDetailOrder,ignoreProperties);
        WXOrderDetailOrder orderInfo = setStatusTextAndHandleOption(marketOrder.getOrderStatus(),wxOrderDetailOrder);
        result.setOrderInfo(orderInfo);

        List<WXOrderDetailExpressInfo> expressInfos = new ArrayList<>();
        result.setExpressInfo(expressInfos);


        return result;
    }

    @Override
    public MarketOrderGoods orderGoods(Integer orderId, Integer goodsId) {
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andGoodsIdEqualTo(goodsId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
        return marketOrderGoods.get(0);
    }

    @Override
    public void orderConfirm(int orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus(Constant.USER_GET_PACKAGE_CODE.shortValue());
        marketOrder.setId(orderId);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public void orderDelete(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus(Constant.ORDER_DELETED.shortValue());
        marketOrder.setDeleted(true);
        marketOrder.setId(orderId);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public void orderCancel(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus(Constant.USER_CANCEL_CODE.shortValue());
        marketOrder.setId(orderId);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public void orderRefund(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus(Constant.APPLY_REFUND_CODE.shortValue());
        marketOrder.setId(orderId);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public Integer orderComment(WXOrderCommentBO param, Integer userId) {
        MarketOrderGoods marketOrderGoods = marketOrderGoodsMapper.selectByPrimaryKey(param.getOrderGoodsId());
        Integer commentStatus = marketOrderGoods.getComment();
        // 如果是-1，则不能评论
        if (commentStatus != 0) {
            return Constant.EXCEPTION_CODE;
        }
        MarketComment comment = new MarketComment();
        /*// 商品类型默认是0，所以我就不设置了，也就是商品类型
        comment.setContent(param.getContent());
        // 设置用户id
        comment.setUserId(userId);
        // 设置是否有图片
        comment.setHasPicture(param.getHasPicture());
        // 设置图片url
        comment.set*/
        String[] ignoreProperties = {"orderGoodsId"};
        BeanUtil.copyProperties(param,comment,ignoreProperties);

        // 设置value_Id 该商品的id
        comment.setValueId(param.getOrderGoodsId());
        // 设置用户id
        comment.setUserId(userId);
        // 设置添加、更新时间
        Date date = new Date();
        comment.setAddTime(date);
        comment.setUpdateTime(date);
        // TODO 做修改，获得自增主键
        marketCommentMapper.insertSelective(comment);

        // 更改orderGoods的comment属性为获得的自增主键
        MarketOrderGoods OrderGoods = new MarketOrderGoods();
        OrderGoods.setComment(comment.getId());
        OrderGoods.setId(param.getOrderGoodsId());
        marketOrderGoodsMapper.updateByPrimaryKeySelective(OrderGoods);
        return Constant.SUCCESS_CODE;
    }

    private WXOrderDetailOrder setStatusTextAndHandleOption(Short orderStatusText, WXOrderDetailOrder wxOrderDetailOrder) {
        HandleOptionBean target = new HandleOptionBean();
        switch (orderStatusText) {
            case 101:
                /**
                 * 用户未支付，可以支付
                 */
                wxOrderDetailOrder.setOrderStatusText(Constant.UNPAID);
                target.setCancel(true);
                target.setPay(true);
                break;
            case 102:
                /**
                 * 用户已取消，可以删除/再次购买
                 */
                wxOrderDetailOrder.setOrderStatusText(Constant.USER_CANCEL);
                target.setDelete(true);
                target.setRebuy(true);
                break;
            case 103:
                /**
                 * 系统已取消，我也不知道啥意思.....就这样吧反正用不到...暂时
                 */
                wxOrderDetailOrder.setOrderStatusText(Constant.SYSTEM_CANCEL);
                break;
            case 201:
                /**
                 * 用户已支付，可以申请退款，
                 */
                wxOrderDetailOrder.setOrderStatusText(Constant.PAID);
                target.setRefund(true);
                break;
            case 202:
                wxOrderDetailOrder.setOrderStatusText(Constant.APPLY_REFUND);
                break;
            case 203:
                wxOrderDetailOrder.setOrderStatusText(Constant.REFUNDED);
                target.setDelete(true);
                target.setRebuy(true);
                break;
            case 301:
                wxOrderDetailOrder.setOrderStatusText(Constant.DELIVERED);
                target.setConfirm(true);
                break;
            case 401:
                // TODO 搞定
                wxOrderDetailOrder.setOrderStatusText(Constant.USER_GET_PACKAGE);
                target.setAftersale(true);
                target.setComment(true);
                // 必须评论了才可以删除订单
                target.setDelete(true);
                target.setRebuy(true);
                break;
            case 402:
                wxOrderDetailOrder.setOrderStatusText(Constant.SYSTEM_GET_PACKAGE);
                //target.setAftersale(true);
                //target.setComment(true);
                target.setDelete(true);
                target.setRebuy(true);
                break;
            default:
                break;
        }
        wxOrderDetailOrder.setHandleOption(target);
        return wxOrderDetailOrder;
    }

    private WXOrderListVO getOrderStatusText(Integer orderStatusText, WXOrderListVO wxOrderDetailOrder) {
        HandleOptionBean target = new HandleOptionBean();
        switch (orderStatusText) {
            case 101:
                /**
                 * 用户未支付，可以支付
                 */
                wxOrderDetailOrder.setOrderStatusText(Constant.UNPAID);
                target.setCancel(true);
                target.setPay(true);
                break;
            case 102:
                /**
                 * 用户已取消，可以删除/再次购买
                 */
                wxOrderDetailOrder.setOrderStatusText(Constant.USER_CANCEL);
                target.setDelete(true);
                target.setRebuy(true);
                break;
            case 103:
                /**
                 * 系统已取消，我也不知道啥意思.....就这样吧反正用不到...暂时
                 */
                wxOrderDetailOrder.setOrderStatusText(Constant.SYSTEM_CANCEL);
                break;
            case 201:
                /**
                 * 用户已支付，可以申请退款，
                 */
                wxOrderDetailOrder.setOrderStatusText(Constant.PAID);
                target.setRefund(true);
                break;
            case 202:
                wxOrderDetailOrder.setOrderStatusText(Constant.APPLY_REFUND);
                break;
            case 203:
                wxOrderDetailOrder.setOrderStatusText(Constant.REFUNDED);
                target.setDelete(true);
                target.setRebuy(true);
                break;
            case 301:
                wxOrderDetailOrder.setOrderStatusText(Constant.DELIVERED);
                target.setConfirm(true);
                break;
            case 401:
                // TODO 搞定
                wxOrderDetailOrder.setOrderStatusText(Constant.USER_GET_PACKAGE);
                target.setAftersale(true);
                target.setComment(true);
                // 必须评论了才可以删除订单
                //target.setDelete(true)
                target.setRebuy(true);
                break;
            case 402:
                wxOrderDetailOrder.setOrderStatusText(Constant.SYSTEM_GET_PACKAGE);
                //target.setAftersale(true);
                //target.setComment(true);
                target.setDelete(true);
                target.setRebuy(true);
                break;
            default:
                break;
        }
        wxOrderDetailOrder.setHandleOption(target);
        return wxOrderDetailOrder;
    }

    private Integer getOrderStatus(Integer parama) {
        Integer orderStatus = null;
        switch (parama) {
            case 0:
                //orderStatus = null;
                break;
            case 1:
                orderStatus = Constant.UNPAID_CODE;
                break;
            case 2:
                orderStatus = Constant.PAID_CODE;
                break;
            case 3:
                orderStatus = Constant.DELIVER_CODE;
                break;
            case 4:
                orderStatus = Constant.USER_GET_PACKAGE_CODE;
                break;
            default:
                break;
        }
        return orderStatus;
    }

}





